<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/27
// +----------------------------------------------------------------------

namespace app\common\services;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\wechat\service\WechatService;
use think\Db;
use think\Exception;
use WeChat\Pay;

/**
 * 钱包服务类
 * Class UserWallet
 * @package app\common\services
 * @author feraner<feraner@163.com>
 * @date 2019/11/27
 */
class UserWalletService
{


    /**
     * user 用户充值兑换发布豆
     * @param $postData
     *
     * @return array|int|string
     * @throws \Exception
     */
    public function rechargeBean($postData)
    {
        $result = [];
        try {
            Db::startTrans();
            //1: 计算兑换的发布豆数量
            $totalMoney = Arr::get($postData, 'totalMoney', 0);
            $beanRate = sysconf('publish_job_bean_rate') ?: 0;
            $giveBeanRate = sysconf('recharge_bean_give_bean') ?: 0;
            if (!$beanRate) {
                throw new \Exception('系统未配置汇豆兑换比率！');
            }
            $buyBean = $totalMoney * $beanRate;
            $giveBean = $totalMoney * $giveBeanRate;

            $orderNo = $this->__createOrderNo(Arr::get($postData, 'user_id'));

            //2：添加用户充值支付记录表
            $chargeId = Db::name('user_charge')
                ->insertGetId([
                    'user_id'        => Arr::get($postData, 'user_id'),
                    'order_no'       => $orderNo,
                    'money'          => $totalMoney,
                    'bean'           => $buyBean + $giveBean,
                    'status'         => 0,
                    'refund_fee'     => '',
                    'type'           => 1,
                    'created_at'     => time(),
                    'updated_at'     => time()
                ]);
            if ($chargeId) {
                //3：添加豆记录
                if ($buyBean) {
                    $result = Db::name('user_recharge_log')
                        ->insertGetId([
                            'user_id'           => Arr::get($postData, 'user_id'),
                            'charge_id'         => $chargeId,
                            'recharge_money'    => $totalMoney,
                            'publish_bean'      => $buyBean,
                            'recharge_rate'     => $beanRate,
                            'give_publish_bean' => $giveBean,
                            'give_rate'         => $giveBeanRate,
                            'type'              => 1,
                            'kind'              => 2,
                            'created_at'        => time(),
                            'updated_at'        => time()
                        ]);
                }
                if ($result) {
                    $result = $chargeId;
                    Db::commit();
                } else {
                    throw new \Exception('添加发布豆记录失败！');
                }
            } else {
                throw new \Exception('生成订单充值表失败!');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }

        return $result;
    }



    /**
     * user 用户充值兑换发布豆 -- 充值活动
     * @param $postData
     *
     * @return array|int|string
     * @throws \Exception
     */
    public function activeRechargeBean($postData)
    {
        $result = [];
        try {
            Db::startTrans();
            //1: 获取充值活动豆配置
            $activeInfo = Db::name('charge_active')
                ->where('id', Arr::get($postData, 'activeId'))
                ->where('status', 1)
                ->where('start_time', '<=', time())
                ->where('end_time', '>=', time())
                ->find() ?: [];

            $totalMoney = Arr::get($postData, 'totalMoney', 0);
            $beanRate = Arr::get($activeInfo, 'publish_bean', 0);
            $giveBeanRate = Arr::get($activeInfo, 'charge_bean', 0);
            if (!$beanRate) {
                throw new \Exception(
                    ApiConstant::CHARGE_ACTIVE_NOT_FUND_STR,
                    ApiConstant::CHARGE_ACTIVE_NOT_FUND
                );
            }
            $buyBean = $totalMoney * $beanRate;
            $giveBean = $totalMoney * $giveBeanRate;

            $orderNo = $this->__createOrderNo(Arr::get($postData, 'user_id'));

            //2：添加用户充值支付记录表
            $chargeId = Db::name('user_charge')
                ->insertGetId([
                    'user_id'        => Arr::get($postData, 'user_id'),
                    'order_no'       => $orderNo,
                    'money'          => $totalMoney,
                    'bean'           => $buyBean + $giveBean,
                    'status'         => 0,
                    'refund_fee'     => '',
                    'type'           => 1,
                    'active_id'      => Arr::get($activeInfo, 'id', 0),
                    'created_at'     => time(),
                    'updated_at'     => time()
                ]);
            if ($chargeId) {
                //3：添加豆记录
                if ($buyBean) {
                    $result = Db::name('user_recharge_log')
                        ->insertGetId([
                            'user_id'           => Arr::get($postData, 'user_id'),
                            'charge_id'         => $chargeId,
                            'recharge_money'    => $totalMoney,
                            'publish_bean'      => $buyBean,
                            'recharge_rate'     => $beanRate,
                            'give_publish_bean' => $giveBean,
                            'give_rate'         => $giveBeanRate,
                            'type'              => 1,
                            'kind'              => 6,
                            'created_at'        => time(),
                            'updated_at'        => time()
                        ]);
                }
                if ($result) {
                    $result = $chargeId;
                    Db::commit();
                } else {
                    throw new \Exception('添加发布豆记录失败！');
                }
            } else {
                throw new \Exception('生成订单充值表失败!');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }

        return $result;
    }








    /**
     * 获取微信支付需要到数据
     *
     * @param $chargeId
     *
     * @return array
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function getWechatInfo($chargeId)
    {
        try {
            $chargeInfo = Db::name('user_charge')
                ->where('id', $chargeId)
                ->where('status', 0)
                ->find() ?: [];
            if ($chargeInfo) {
                $userInfo = Db::name('user')->where('id', Arr::get($chargeInfo, 'user_id'))
                    ->find() ?: [];
                $wechatPayServer = WechatService::WePayOrder();

                $orderResult = $wechatPayServer->create([
                    'body'             => '购买汇豆',
                    'out_trade_no'     => Arr::get($chargeInfo, 'order_no'),
                    'total_fee'        => (Arr::get($chargeInfo, 'money', 0) * 100),
                    'openid'           => Arr::get($userInfo, 'wechat_openid'),
                    'trade_type'       => 'JSAPI',
                    'notify_url'       => config('api_host_name') . 'api/user/buyBeanNotify',
                    'attach'           => 'activeId=' . Arr::get($chargeInfo, 'active_id', 0)
                ]);

                // 创建JSAPI参数签名
                $jsApiParams = $wechatPayServer->jsapiParams(Arr::get($orderResult, 'prepay_id', 0));

                return [
                    'chargeInfo'            => $chargeInfo,
                    'jsApiParams'           => $jsApiParams,
                ];
            }
            throw new \Exception('充值订单信息错误');
        } catch (\Exception $e) {
            throw $e;
        }
    }
















    /**
     * 生成订单标号
     * @return mixed
     */
    private function __createOrderNo($userId)
    {
        return str_replace('.', '', $userId . uniqid('hd', true));
    }





}
